#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#define INIT_MAGIC 0xdb

static void
dump_formatted_out(const char *cat_filename)
{
	struct stat cat_stat;
	char *text;
	char *ptr;
	char *p2;
	unsigned char mgk = INIT_MAGIC;
	long nl;
	char chr_num[32];
	int c_offset = 0;
	char *start_line;
	FILE *f;
	long n;
	if (stat(cat_filename, &cat_stat) == -1) {
		perror("stat failed");
		return;
	}
	f = fopen(cat_filename, "r");
	if (f == NULL) {
		perror("fopen failed");
		return;
	}
	text = (char *)malloc(cat_stat.st_size + 1);
	if ((n = fread(text, 1, cat_stat.st_size, f)) !=
			(long)cat_stat.st_size) {
		fprintf(stderr, "warning: partial read (%lu instead %lu)\n", n,
				cat_stat.st_size);
		perror("fread failure");
	}
	fclose(f);
	text[cat_stat.st_size] = '\0';
	for (ptr = text, nl = 0; nl < cat_stat.st_size; ++ ptr, ++ nl)
		*ptr ^= mgk ++;
	ptr = strchr(text, '\n');
	if (ptr == NULL) {
		fputs("cannot parse input\n", stderr);
		free(text);
		return;
	}
	nl = 1;
	++ ptr;
	do {
		start_line = ptr;
		ptr = strchr(ptr, '\n');
		if (ptr == NULL) {
			fputs("bad input\n", stderr);
			break;
		}
		*ptr = '\0';
		p2 = strrchr(start_line, ' ');
		if (p2 == NULL) {
			fputs("bad input (space)\n", stderr);
			break;
		}
		strcpy(chr_num, p2 + 1);
		printf("%li. offset %i, %s\n", nl, c_offset, start_line);
		c_offset += atoi(chr_num);
		*ptr = '\n';
		++ nl;
		++ ptr;
	} while (*ptr);
	free(text);
}

int
main(int argc, char **argv)
{
	unsigned char mgk = INIT_MAGIC;
	FILE *f = fopen(argv[1], "r");
	size_t n;
	size_t i;
	char buf[512];
	if (argc < 2)
		return 1;
	if (argc > 2 && strcmp(argv[2], "-f") == 0) {
		dump_formatted_out(argv[1]);
		return 0;
	}
	if (!f) {
		perror("fopen failed");
		return 1;
	}
	do {
		n = fread(buf, 1, sizeof(buf), f);
		for (i = 0; i < n; ++ i)
			buf[i] ^= mgk ++;
		fwrite(buf, 1, n, stdout);
	} while (n == sizeof(buf));
	fclose(f);
	putchar('\n');
	return 0;
}
